package com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer;

import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.lancoo.znbkxx.teacher.R;

import java.io.IOException;

public class ChildAudioPlayer implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener, DefaultLifecycleObserver {

    // 单任务线程池
    private AnimationDrawable animationDrawable;
    private void startAnim() {
        ivPlay.clearAnimation();
        animationDrawable = (AnimationDrawable) activity.getResources().getDrawable(R.drawable.anim_laba); // 1. 获取动画对象
        ivPlay.setImageDrawable(animationDrawable);
        animationDrawable.start();
    }

    private void stopAnim() {
        if(animationDrawable!=null) {
            animationDrawable.stop();
            ivPlay.clearAnimation();
            animationDrawable.selectDrawable(0);
        }
    }

    private AppCompatActivity activity;
    public MediaPlayer mediaPlayer; // 媒体播放器
    private  ImageView ivPlay;
    private boolean isPrepare = false;
    private PlayListener playListener;

    // 初始化播放器
    public ChildAudioPlayer(AppCompatActivity activity, String musicUrl, ImageView ivPlay, PlayListener playListener) {
        super();
        this.activity = activity;
        this.ivPlay = ivPlay;
        ivPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取当前图片ConstantState类对象
                Drawable.ConstantState t1 = ivPlay.getDrawable().getCurrent().getConstantState();
                //找到需要比较的图片ConstantState类对象
                Drawable.ConstantState t2 = activity.getDrawable(R.mipmap.ic_music_loading).getConstantState();
                if (t1.equals(t2)) {
                    return;
                } else {
                    if (isPrepare) {
                        if (mediaPlayer.isPlaying()) {
                            pauseChildAudio();
                        } else {
                            startAnim();
                            mediaPlayer.start();
                            playListener.onStartPlay();
                        }
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //更改UI；
                                playUrl(musicUrl);
                            }
                        });

                    }
                }
            }
        });
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        this.playListener = playListener;

    }

    public void play() {
        if (isPrepare) {
            if (mediaPlayer.isPlaying()) {
                pauseChildAudio();
            } else {
                mediaPlayer.start();
            }
        }


    }

    public void rePlay() {
        mediaPlayer.seekTo(0);
    }

    /**
     * @param url url地址
     */
    private void playUrl(String url) {
        try {
            startAnim();
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url); // 设置数据源
            mediaPlayer.prepare(); // prepare自动播放
            mediaPlayer.start();
            playListener.initFirstPlay();
        } catch (IllegalArgumentException | SecurityException | IOException | IllegalStateException e) {
            e.printStackTrace();
        }

    }

    // 暂停
    public void pauseChildAudio() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            stopAnim();
            mediaPlayer.seekTo(0);
            mediaPlayer.pause();
        }
    }

    // 停止
    public void DestoryChildAudio() {
        stopAnim();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        pauseChildAudio();
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        pauseChildAudio();
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        pauseChildAudio();
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        pauseChildAudio();
    }


    @Override
    public void onPrepared(MediaPlayer mp) {
        isPrepare = true;
        mediaPlayer.seekTo(0);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        stopAnim();
        playListener.onFinishPlay();
    }

    public interface PlayListener {
        void onFinishPlay();
        void onStartPlay();
        void initFirstPlay();
    }

    public boolean setPlaySpeed(float speed) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                PlaybackParams params = mediaPlayer.getPlaybackParams();
                params.setSpeed(speed);
                mediaPlayer.setPlaybackParams(params);
                return true;
            } catch (Exception e) {
                Log.e("TAG", "setPlaySpeed: ", e);
                return false;
            }
        }
        return false;
    }

}